<template>
  <div class="manyBox">
    <el-button class="addBtn" type="success">添加动态参数</el-button>

    <!-- 表格 -->
    <el-table default-expand-all :data="bindList" style="width: 698px" border>
      <el-table-column type="expand">
        <template #default="{ row }">
          <div class="params">
            <el-tag class="ml-2" type="success" closable v-for="(item,index) in row.bttr_vals" :key="index">{{ item }}</el-tag>

            <el-input
              v-if="row.is_add"
              ref="InputRef"
              v-model="row.add"
              class="ml-1 w-20 ipt"
              size="small"
              @blur="colseIpt(row)"
              @keydown.enter="addHandler(row)"
            />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
              + New Tag
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="参数名称" prop="attr_name" width="180"/>
      <el-table-column label="动态参数" prop="bttr_vals" width="300"/>
      <el-table-column label="操作" width="170">
        <template #default>
          <el-button type="warning">编辑</el-button>
          <el-button type="danger" @click="handleClose(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'oa_many',
  props: ['list', 'id'],
  data () {
    return {
    }
  },
  methods: {
    // 添加参数显示input框
    showInput (info) {
      info.is_add = true
    },
    // input失去焦点
    colseIpt (info) {
      info.is_add = false
      info.add = ''
    },
    // 添加参数
    async addHandler (info) {
      const data = {
        attr_sel: 'many',
        attr_name: info.attr_name,
        attr_vals: [...info.bttr_vals, info.add].toString()
      }
      const res = await this.$http.post(`categories/${this.id}/attributes`, data)
      console.log(res)
      if (res.meta.status !== 200) return
      this.$emit('addFinsh')
      ElMessage({
        showClose: true,
        message: '添加成功',
        type: 'success'
      })
    },
    // 删除数据
    async handleClose (info) {
      const res = await this.$http.delete(`categories/${info.cat_id}/attributes/${info.attr_id}`)
      if (res.meta.status !== 200) return
      this.$emit('addFinsh')
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success'
      })
    }
  },
  computed: {
    // 处理attr_vals数据
    bindList () {
      const bindList = this.list.map(item => {
        item.bttr_vals = item.attr_vals.split(',')
        // 去除数组中的空项
        item.bttr_vals = item.bttr_vals.filter(str => str)

        item.is_add = false
        item.add = ''
        return item
      })
      return bindList
    }
  }
}
</script>
<style scoped lang="scss">
.addBtn{
  margin-bottom: 10px;
}
.params{
  margin-left: 20px;
}
.ml-2{
  margin: 10px;
}
.ipt{
  display: inline;
}
</style>
